<template>
  <div class="w1 h1 main_content">
    <div class="search-content">
      <Col class="panel search-panel" :span="24" style="padding-left:5px;">
        <Form :label-width="70" inline :model="formHeader">
          <Col :span="24">
            <FormItem label="选择城市:">
              <Select
                clearable
                v-model="formHeader.cityId"
                style="width: 200px;"
                @on-change="cityChange"
              >
                <Option
                  :value="item.id"
                  v-for="(item, index) in citylist"
                  :key="index"
                  :label="item.name"
                ></Option>
              </Select>
            </FormItem>
            <FormItem label="企业名称:" v-if="userRole != 'ROLE_DEMO'">
              <Select
                clearable
                v-model="formHeader.companyId"
                style="width: 200px;"
                @on-change="formHeader.deviceName = ''"
              >
                <Option
                  :value="item.id"
                  v-for="(item, index) in companyList"
                  :key="index"
                  :label="item.name"
                ></Option>
              </Select>
            </FormItem>
            <FormItem label="企业名称:" v-if="userRole == 'ROLE_DEMO'">
              <Select
                clearable
                v-model="formHeader.companyId"
                style="width: 200px;"
                @on-change="formHeader.deviceName = ''"
              >
                <Option
                  :value="item.id"
                  v-for="(item, index) in companyList"
                  :key="index"
                  :label="item.alias"
                ></Option>
              </Select>
            </FormItem>
            <FormItem label="设备名称:">
              <Input
                style="width: 190px;"
                v-model="formHeader.deviceName"
                placeholder="设备名称..."
                clearable
              ></Input>
            </FormItem>
          </Col>
          <Col :span="24">
            <FormItem label="设备状态:">
              <RadioGroup v-model="formHeader.state" type="button">
                <Radio label="">全部</Radio>
                <Radio label="1">正常</Radio>
                <Radio label="2">预警</Radio>
                <Radio label="3">告警</Radio>
                <Radio label="4">故障</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="是否在线:">
              <RadioGroup v-model="formHeader.online" type="button">
                <Radio :label="null">全部</Radio>
                <Radio label="1">在线</Radio>
                <Radio label="0">离线</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem class="margin-left-20">
              <Button
                type="primary"
                @click.stop="handleSearch"
                style="margin-right:20px;"
                >查询</Button
              >
              <Button
                type="primary"
                :disabled="userRole === 'ROLE_DEMO'"
                @click="buildNewDevice"
                >新增设备</Button
              >
            </FormItem>
          </Col>
        </Form>
      </Col>
    </div>
    <div class="w1 scroll__content device_content">
      <Row class="scroll-content__row">
        <Col class="panel table-panel" :span="24">
          <Table
            :columns="userRole == 'ROLE_DEMO' ? columnsOfDemo : columns"
            :data="tableData"
            border
            :loading="pageInfo.loading"
          ></Table>
        </Col>
        <!-- 分页 -->
        <Col
          class="panel page-panel cf"
          style="margin-bottom: 10px;"
          :span="24"
        >
          <Page
            :total="pageInfo.total"
            page-size="15"
            :current.sync="pageInfo.page"
            class="fr"
            @on-change="switchThePaging"
          ></Page>
        </Col>
        <Col span="24" class="page-bottom "> </Col>
        <!-- 新建设备 -->
        <Modal
          width="800"
          footer-hide
          title="新建设备"
          v-model="dialogVisibleNew"
        >
          <transition name="dialog-form-fade">
            <!-- <CreateNewDevice
              v-if="dialogVisibleNew"
              @save="newBuildSuccess"
              @off="newBuildOff"
            /> -->
            <new-device-form
              v-if="dialogVisibleNew"
              @on-save="newBuildSuccess"
              @on-off="newBuildOff"
            ></new-device-form>
          </transition>
        </Modal>
      </Row>
    </div>
  </div>
</template>
<script>
import { hardwareTypes, collectTypes } from "./utils";
import newDeviceForm from "./newDeviceForm";

import {
  getCityListOfNew,
  getDeviceListOfNew,
  getCompanyListOfNew,
  stopDevice,
  startDevice,
  editDevice,
  removeDevice,
  getGroupList,
  addDevice
} from "@/api";

import { generatedColumns } from "./utils";

import { mapState } from "vuex";

export default {
  components: { "new-device-form": newDeviceForm },
  created() {
    const sessionData = JSON.parse(sessionStorage.getItem("searchKey")),
      vm = this;
    if (!!sessionData) {
      vm.formHeader = Object.assign(vm.formHeader, sessionData);
      vm.pageInfo.page = sessionData.page;
    }
  },

  async mounted() {
    sessionStorage.removeItem("deviceSearchInfo");
    await this._getCityListAll();
    if (!!this.formHeader.cityId) {
      await this._getCompanyList();
    }
    !!this.$route.query.page && (this.pageInfo.page = this.$route.query.page);
    this._getDeviceList();
    sessionStorage.removeItem("searchKey");
  },
  computed: {
    ...mapState({
      userRole: state => state.userInfo.rname
    })
  },
  data() {
    const vm = this;
    return {
      dialogVisibleNew: false,
      formHeader: {
        cityId: "",
        companyId: "",
        online: null,
        deviceName: "",
        state: ""
      },
      pageInfo: {
        page: 1,
        total: 0,
        loading: false
      },
      citylist: [],
      companyList: [],
      tableData: [],
      groupList: [],
      columnsOfDemo: [...generatedColumns(vm, true)],
      columns: [...generatedColumns(vm, false)]
    };
  },

  methods: {
    newBuildSuccess() {
      this.dialogVisibleNew = false;
      this._getDeviceList();
    },

    newBuildOff() {
      this.dialogVisibleNew = false;
    },

    buildNewDevice() {
      const vm = this;
      vm.dialogVisibleNew = true;
    },

    handleSearch() {
      const vm = this;
      vm.pageInfo.page = 1;
      vm._getDeviceList();
    },

    // 停止设备
    _stopDevice(row) {
      let vm = this;
      let id = row.id;
      let deviceId = row.deviceId;
      let port = row.port;
      let hardwareType = row.hardwareType;
      let params = {
        id,
        deviceId,
        port,
        hardwareType
      };
      stopDevice(params).then(res => {
        if (res.code == 200) {
          vm.$Message.success("设备停止成功");
          vm._getDeviceList();
        } else {
          vm.$Message.error(res.message);
        }
      });
    },

    // 启动设备
    _startDevice(row) {
      let vm = this;
      let id = row.id;
      let deviceId = row.deviceId;
      let port = row.port;
      let hardwareType = row.hardwareType;
      let params = {
        id,
        deviceId,
        port,
        hardwareType
      };
      startDevice(params).then(res => {
        if (res.code == 200) {
          vm.$Message.success("设备启动成功");
          vm._getDeviceList();
        } else {
          vm.$Message.error(res.message);
        }
      });
    },

    // 删除设备
    handleDelete(row) {
      let vm = this;
      let id = row.id;
      removeDevice(id).then(res => {
        if (res.code == 200) {
          vm.$Message.success("操作成功");
          vm._getDeviceList();
        } else {
          vm.$Message.error(res.message);
        }
      });
    },

    switchThePaging(index) {
      let vm = this;
      vm.pageInfo.page = index;
      vm._getDeviceList();
    },

    // 获取城市列表
    async _getCityListAll() {
      let vm = this;
      await getCityListOfNew({}).then(res => {
        if (res.code == 200) {
          vm.citylist = res.data;
        }
      });
    },

    // 城市变更，企业列表联动
    cityChange(id) {
      this.companyList = [];
      this.formHeader.companyId = "";
      if (!!id) {
        this.formHeader.cityId = id;
        this._getCompanyList();
      }
    },

    // 获取企业列表
    _getCompanyList() {
      let vm = this;
      let params = {
        cityId: vm.formHeader.cityId
      };
      return new Promise((resolve, reject) => {
        getCompanyListOfNew(params).then(res => {
          if (res.code == 200) {
            vm.companyList = res.data.list;
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    _getDeviceList() {
      const _t = this;
      _t.pageInfo.loading = true;
      let params = Object.assign({}, _t.formHeader, {
        size: 15,
        page: _t.pageInfo.page
      });
      getDeviceListOfNew(params).then(res => {
        if (res.code == 200) {
          _t.tableData = res.data.list;
          _t.pageInfo.total = res.data.total;
          setTimeout(_ => {
            _t.pageInfo.loading = false;
          }, 500);
        }
      });
    }
  }
};
</script>
